package co.yixiang.yshop.module.crm.service.crmcloudcall;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import co.yixiang.yshop.framework.common.enums.ShopCommonEnum;
import co.yixiang.yshop.framework.common.exception.ErrorCode;
import co.yixiang.yshop.framework.redis.util.redis.RedisUtil;
import co.yixiang.yshop.framework.security.core.util.SecurityFrameworkUtils;
import co.yixiang.yshop.module.crm.cloud.MoorCloudCall;
import co.yixiang.yshop.module.crm.cloud.vo.CallReqVo;
import co.yixiang.yshop.module.crm.dal.dataobject.crmcloudcalllog.CrmCloudcallLogDO;
import co.yixiang.yshop.module.crm.dal.dataobject.crmcustomer.CrmCustomerDO;
import co.yixiang.yshop.module.crm.dal.mysql.crmcloudcalllog.CrmCloudcallLogMapper;
import co.yixiang.yshop.module.crm.dal.mysql.crmcustomer.CrmCustomerMapper;
import co.yixiang.yshop.module.crm.enums.CallTypesEnum;
import co.yixiang.yshop.module.crm.enums.TypesEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import co.yixiang.yshop.module.crm.controller.admin.crmcloudcall.vo.*;
import co.yixiang.yshop.module.crm.dal.dataobject.crmcloudcall.CrmCloudcallDO;
import co.yixiang.yshop.framework.common.pojo.PageResult;
import co.yixiang.yshop.framework.common.pojo.PageParam;
import co.yixiang.yshop.framework.common.util.object.BeanUtils;

import co.yixiang.yshop.module.crm.dal.mysql.crmcloudcall.CrmCloudcallMapper;

import static co.yixiang.yshop.framework.common.exception.util.ServiceExceptionUtil.exception;
import static co.yixiang.yshop.module.crm.enums.ErrorCodeConstants.*;

/**
 * 云呼坐席管理 Service 实现类
 *
 * @author yshop
 */
@Service
@Validated
public class CrmCloudcallServiceImpl implements CrmCloudcallService {

    @Resource
    private CrmCloudcallMapper cloudcallMapper;
    @Resource
    private CrmCloudcallLogMapper cloudcallLogMapper;
    @Resource
    private CrmCustomerMapper customerMapper;


    @Override
    public Long createCloudcall(CrmCloudcallSaveReqVO createReqVO) {
        CrmCloudcallDO crmCloudcallDO = cloudcallMapper.selectOne(new LambdaQueryWrapper<CrmCloudcallDO>()
                .eq(CrmCloudcallDO::getAdminId, createReqVO.getAdminId()));
        if(crmCloudcallDO != null){
            throw exception(new ErrorCode(202412103,"当前员工已经绑定过坐席"));
        }
        // 插入
        CrmCloudcallDO cloudcall = BeanUtils.toBean(createReqVO, CrmCloudcallDO.class);
        cloudcallMapper.insert(cloudcall);
        // 返回
        return cloudcall.getId();
    }

    @Override
    public void updateCloudcall(CrmCloudcallSaveReqVO updateReqVO) {
        CrmCloudcallDO crmCloudcallDO = cloudcallMapper.selectOne(new LambdaQueryWrapper<CrmCloudcallDO>()
                .ne(CrmCloudcallDO::getId,updateReqVO.getId())
                .eq(CrmCloudcallDO::getAdminId, updateReqVO.getAdminId()));
        if(crmCloudcallDO != null){
            throw exception(new ErrorCode(202412104,"当前员工已经绑定过坐席"));
        }
        // 校验存在
        validateCloudcallExists(updateReqVO.getId());
        // 更新
        CrmCloudcallDO updateObj = BeanUtils.toBean(updateReqVO, CrmCloudcallDO.class);
        cloudcallMapper.updateById(updateObj);
    }

    @Override
    public void deleteCloudcall(Long id) {
        // 校验存在
        validateCloudcallExists(id);
        // 删除
        cloudcallMapper.deleteById(id);
    }

    private void validateCloudcallExists(Long id) {
        if (cloudcallMapper.selectById(id) == null) {
            throw exception(CLOUDCALL_NOT_EXISTS);
        }
    }

    @Override
    public CrmCloudcallDO getCloudcall(Long id) {
        return cloudcallMapper.selectById(id);
    }

    @Override
    public PageResult<CrmCloudcallRespVO> getCloudcallPage(CrmCloudcallPageReqVO pageReqVO) {
        return cloudcallMapper.selectPage(pageReqVO);
    }

    @Override
    public void doCall(Long id, String source, String phone) {
        if (StrUtil.isEmpty(phone)) {
            throw exception(new ErrorCode(202412100, "联系人手机不能为空"));
        }
        String cloudAccountId = RedisUtil.get("cloudAccountId");
        String cloudSecret = RedisUtil.get("cloudSecret");
        if (StrUtil.isEmpty(cloudAccountId) || StrUtil.isEmpty(cloudSecret)) {
            throw exception(new ErrorCode(202412102, "请先配置云呼叫参数"));
        }
        String name = "";
        if(TypesEnum.CUSTOMER.getValue().equals(source)){
            CrmCustomerDO customerDO = customerMapper.selectById(id);
            name = customerDO.getName();
        }
        Long adminId = SecurityFrameworkUtils.getLoginUserId();
        CrmCloudcallDO crmCloudcallDO = cloudcallMapper.selectOne(new LambdaQueryWrapper<CrmCloudcallDO>()
                .eq(CrmCloudcallDO::getAdminId, adminId)
                .eq(CrmCloudcallDO::getStatus, ShopCommonEnum.IS_STATUS_1.getValue()));
        if (crmCloudcallDO == null) {
            throw exception(new ErrorCode(202412101, "当前登录员工没有绑定坐席"));
        }

        MoorCloudCall moorCloudCall = new MoorCloudCall(cloudAccountId, cloudSecret);
        CallReqVo callReqVo = CallReqVo.builder()
                .fromExten(crmCloudcallDO.getFromExten())
                .exten(phone)
                .extenType(CallTypesEnum.LOCAL.getValue()).build();
        JSONObject jsonObject = moorCloudCall.diaLout(callReqVo);


        //创建呼叫记录
        CrmCloudcallLogDO cloudcallLog =  CrmCloudcallLogDO.builder()
                .adminId(adminId)
                .name(name)
                .source(source)
                .sourceId(id)
                .fromExten(crmCloudcallDO.getFromExten())
                .calledNo(phone)
                .actionId(jsonObject.get("ActionID").toString())
                .build();
        cloudcallLogMapper.insert(cloudcallLog);

    }
}